package com.ts.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpClientUtil {


	public static String sendHttpGet(String completeUrl) throws Exception {
		HttpURLConnection conn = null;
		StringBuilder builder = new StringBuilder();
		try {
			URL url = new URL(completeUrl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setRequestProperty("type", "submit");
			conn.setDoOutput(true);
			conn.setReadTimeout(10000);
			conn.connect();
			if (conn.getResponseCode() != 200) {
				return "{'success':false, 'content':'http 请求错误'}";
			}
			BufferedReader in = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), "UTF-8"));
			String inputLine = "";
			while ((inputLine = in.readLine()) != null) {
				builder.append(inputLine);
			}
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e);
		} finally {
			try {
				conn.disconnect();
			} catch (Exception e) {
			}
		}
		return builder.toString();
	}

	/**
	 * 发送请求，得到返回值
	 */
	public static String sendRequest(String sign, String completeUrl, String token) throws Exception {

		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		String result = "";

		try{
			httpClient = HttpClients.createDefault();
			HttpGet httpGet = new HttpGet(completeUrl);
			httpGet.addHeader("Authorization","Bearer " + token);
			httpGet.addHeader("apigs_ca_sign",sign);
			RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(60000).setSocketTimeout(60000).build();
			httpGet.setConfig(requestConfig);

			response = httpClient.execute(httpGet);
			HttpEntity entity = response.getEntity();
			result = EntityUtils.toString(entity);

		}catch (ClientProtocolException e){
			e.printStackTrace();
		}catch (IOException e){
			e.printStackTrace();
		}finally {
			if(null != response){
				response.close();
			}
			if(null != httpClient){
				httpClient.close();
			}
		}
		return result;
	}

	public static void main(String[] args){

		try {
			String a = HttpClientUtil.sendHttpGet("http://61.131.207.68:31007/getBusDistanceList?note=20200420");
			File txt=new File("C:\\project\\gongjiao\\10.车辆单趟运营明细0420.txt");
			if(!txt.exists()){
				txt.createNewFile();
			}
			byte bytes[]=new byte[512];
			bytes=a.getBytes();
			int b=bytes.length;   //是字节的长度，不是字符串的长度
			FileOutputStream fos=new FileOutputStream(txt);
			fos.write(bytes,0,b);
			fos.write(bytes);
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

